<template>
  <div class="food-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
              特色美食
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              探索贵港地道美食，品味舌尖上的风味
            </p>
          </div>
          <el-button
            class="back-btn"
            type="primary"
            plain
            @click="router.push('/')"
          >
            <el-icon class="mr-1"><Back /></el-icon>
            返回首页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 搜索和筛选区 -->
          <div
            class="search-filter-section bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-8"
          >
            <!-- 搜索框 -->
            <div class="search-box mb-6">
              <el-input
                v-model="searchQuery"
                placeholder="搜索美食名称或关键词"
                class="search-input"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>

            <!-- 筛选条件 -->
            <div class="filter-conditions flex items-center gap-4">
              <!-- 分类筛选 -->
              <el-select
                v-model="filterConditions.category"
                placeholder="美食分类"
                clearable
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>

              <!-- 区域筛选 -->
              <el-select
                v-model="filterConditions.area"
                placeholder="所在区域"
                clearable
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="area in areas"
                  :key="area.value"
                  :label="area.label"
                  :value="area.value"
                />
              </el-select>

              <!-- 排序方式 -->
              <el-select
                v-model="filterConditions.sortBy"
                placeholder="排序方式"
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="sort in sortOptions"
                  :key="sort.value"
                  :label="sort.label"
                  :value="sort.value"
                />
              </el-select>
            </div>
          </div>

          <!-- 美食列表 -->
          <div class="food-list space-y-6" v-loading="loading">
            <div
              v-for="food in displayFoodList.items"
              :key="food.id"
              class="food-card bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-all duration-300 transform hover:-translate-y-1 cursor-pointer"
              @click="handleFoodClick(food)"
            >
              <div class="flex">
                <div class="food-image-wrapper w-1/3">
                  <el-image
                    :src="food.image"
                    class="w-full h-48 object-cover"
                    fit="cover"
                  >
                    <template #placeholder>
                      <div class="image-placeholder">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="food-content flex-1 p-6">
                  <div class="food-meta flex items-center gap-4 mb-3">
                    <el-tag
                      size="small"
                      :type="food.isRecommended ? 'danger' : ''"
                      effect="light"
                    >
                      {{ food.isRecommended ? "推荐" : "美食" }}
                    </el-tag>
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                      {{ food.category }}
                    </span>
                  </div>
                  <h3
                    class="food-title text-xl font-medium text-gray-900 dark:text-white mb-3 line-clamp-1"
                  >
                    {{ food.name }}
                  </h3>
                  <p
                    class="food-description text-gray-600 dark:text-gray-400 line-clamp-2 mb-4"
                  >
                    {{ food.description }}
                  </p>
                  <div class="food-footer flex items-center justify-between">
                    <div
                      class="food-location flex items-center text-sm text-gray-500 dark:text-gray-400"
                    >
                      <el-icon class="mr-1"><Location /></el-icon>
                      {{ food.location }}
                    </div>
                    <div class="mt-2 flex justify-between items-center">
                      <div class="flex items-center space-x-2 text-gray-500 dark:text-gray-400">
                        <span class="flex items-center">
                          <el-icon><View /></el-icon>
                          <span class="ml-1">{{ formatNumber(food.views) }}</span>
                        </span>
                        <span 
                          class="flex items-center cursor-pointer" 
                          @click.stop="handleLike(food)"
                        >
                          <el-icon :class="{ 'text-red-500': food.isLiked }">
                            <Star />
                          </el-icon>
                          <span class="ml-1">{{ formatNumber(food.likes) }}</span>
                        </span>
                      </div>
                      <el-tag size="small" effect="plain">{{ food.category }}</el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && !displayFoodList.items.length"
              description="暂无相关美食"
            >
              <el-button type="primary" @click="resetFilters"
                >清除筛选</el-button
              >
            </el-empty>

            <!-- 分页 -->
            <div
              v-if="total > 0"
              class="pagination-wrapper flex justify-center mt-8"
            >
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 推荐美食 -->
          <div
            class="recommended-food bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Star /></el-icon>
              推荐美食
            </h3>
            <div class="recommended-food-list space-y-4">
              <div
                v-for="food in recommendedFood"
                :key="food.id"
                class="recommended-food-item flex items-start gap-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-lg transition-all duration-300"
                @click="handleFoodClick(food)"
              >
                <el-image
                  :src="food.image"
                  class="w-20 h-20 rounded-lg object-cover flex-shrink-0"
                />
                <div class="flex-1 min-w-0">
                  <h4
                    class="text-sm font-medium text-gray-900 dark:text-white line-clamp-2 mb-1"
                  >
                    {{ food.name }}
                  </h4>
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ food.category }}
                  </div>
                  <div
                    class="mt-1 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400"
                  >
                    <span class="flex items-center">
                      <el-icon class="mr-1"><View /></el-icon>
                      {{ formatNumber(food.views) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 美食分类 -->
          <div
            class="food-categories bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Menu /></el-icon>
              美食分类
            </h3>
            <div class="categories-list space-y-2">
              <div
                v-for="category in categories"
                :key="category.value"
                class="category-item flex items-center justify-between p-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-all duration-300"
                @click="handleCategoryClick(category)"
              >
                <span class="text-gray-700 dark:text-gray-300">{{
                  category.label
                }}</span>
                <el-tag size="small" :type="category.type" effect="light">{{
                  category.count
                }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import {
  Search,
  Back,
  View,
  Star,
  Menu,
  Picture,
  Location,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import service from "@/api/axios";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const allFoodData = ref([]); // 储存所有获取到的食品数据

// 筛选条件
const filterConditions = reactive({
  category: "",
  area: "",
  sortBy: "recommended",
});

// 美食分类
const categories = [
  { label: "特色小吃", value: "snack", type: "", count: 125 },
  { label: "传统美食", value: "traditional", type: "success", count: 89 },
  { label: "地方特色", value: "local", type: "warning", count: 156 },
  { label: "甜品饮品", value: "dessert", type: "danger", count: 78 },
  { label: "其他美食", value: "other", type: "info", count: 45 },
];

// 区域选项
const areas = [
  { label: "港北区", value: "gangbei" },
  { label: "港南区", value: "gangnan" },
  { label: "覃塘区", value: "qintang" },
  { label: "平南县", value: "pingnan" },
  { label: "桂平市", value: "guiping" },
];

// 排序选项
const sortOptions = [
  { label: "推荐排序", value: "recommended" },
  { label: "最多浏览", value: "most_viewed" },
  { label: "最多点赞", value: "most_liked" },
];

// 测试数据（备用）
const testFoodData = [
  {
    id: 1,
    name: "贵港艇仔粥",
    description: "使用新鲜的河鲜熬制，口感鲜美，是贵港最具特色的传统美食之一。",
    image: "/images/food/food1.jpg",
    category: "特色小吃",
    location: "贵港市港北区",
    isRecommended: true,
    views: 15680,
    likes: 2360,
  },
  {
    id: 2,
    name: "荷叶粉",
    description:
      "采用上等大米制作，配以特制酱料，清香可口，是贵港传统风味小吃。",
    image: "/images/food/food2.jpg",
    category: "传统美食",
    location: "贵港市港南区",
    isRecommended: true,
    views: 12460,
    likes: 1890,
  },
];

// 测试推荐美食数据（备用）
const testRecommendedFood = [
  {
    id: 1,
    name: "贵港艇仔粥",
    image: "/images/food/food1.jpg",
    category: "特色小吃",
    views: 15680,
  },
  {
    id: 2,
    name: "荷叶粉",
    image: "/images/food/food2.jpg",
    category: "传统美食",
    views: 12460,
  },
  {
    id: 3,
    name: "贵港酿豆腐",
    image: "/images/food/food3.jpg",
    category: "地方特色",
    views: 10240,
  },
];

// 美食列表数据
const foodList = ref([]);
// 推荐美食数据
const recommendedFood = ref([]);

// 计算过滤和排序后的完整列表
const filteredAndSortedList = computed(() => {
  // 确保allFoodData.value是数组
  if (!Array.isArray(allFoodData.value)) {
    return [];
  }
  
  const filteredList = allFoodData.value.filter(item => {
    if (!item) return false;
    
    // 搜索过滤
    const searchMatch = searchQuery.value ? 
      (item.name?.toLowerCase().includes(searchQuery.value.toLowerCase()) || 
      item.description?.toLowerCase().includes(searchQuery.value.toLowerCase())) : 
      true;
    
    // 分类过滤
    const categoryMatch = filterConditions.category ? 
      item.category === categories.find(c => c.value === filterConditions.category)?.label : 
      true;
    
    // 区域过滤
    const areaMatch = filterConditions.area ? 
      item.location?.includes(areas.find(a => a.value === filterConditions.area)?.label) : 
      true;
    
    return searchMatch && categoryMatch && areaMatch;
  });
  
  // 排序
  let sortedList = [...filteredList];
  if (filterConditions.sortBy === 'most_viewed') {
    sortedList.sort((a, b) => (b.views || 0) - (a.views || 0));
  } else if (filterConditions.sortBy === 'most_liked') {
    sortedList.sort((a, b) => (b.likes || 0) - (a.likes || 0));
  } else {
    // 推荐排序：把推荐的放前面
    sortedList.sort((a, b) => {
      if (a.isRecommended && !b.isRecommended) return -1;
      if (!a.isRecommended && b.isRecommended) return 1;
      return (b.views || 0) - (a.views || 0); // 如果推荐状态相同，则按浏览量排序
    });
  }
  
  return sortedList;
});

// 监听过滤排序后的列表长度变化，更新total
watch(() => filteredAndSortedList.value.length, (newLength) => {
  total.value = newLength;
}, { immediate: true });

// 计算当前页显示的列表
const displayFoodList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const list = filteredAndSortedList.value.slice(start, start + pageSize.value);
  return {
    items: list || []
  };
});

// 获取美食列表
const getFoodList = async () => {
  loading.value = true;
  
  // 直接使用测试数据，避免API请求问题
  allFoodData.value = testFoodData;
  console.log("使用测试数据", testFoodData);
  
  try {
    // 尝试获取实际数据，但即使失败也已经有测试数据了
    const response = await service.get("/public/foods");
    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      // 确保每个食品项目都有views和likes属性，如果不存在或为0则添加随机值
      const processedData = response.data.map(item => {
        if (item.views === undefined || item.views === null || isNaN(item.views) || item.views === 0) {
          item.views = Math.floor(Math.random() * 19500) + 500;
        }
        if (item.likes === undefined || item.likes === null || isNaN(item.likes) || item.likes === 0) {
          item.likes = Math.floor(Math.random() * 2950) + 50;
        }
        return item;
      });
      allFoodData.value = processedData;
    }
  } catch (error) {
    console.error("获取美食列表失败:", error);
    // 已经使用了测试数据，这里不需要再次设置
  } finally {
    loading.value = false;
  }
};

// 获取推荐美食
const getRecommendedFood = async () => {
  // 直接使用测试数据
  recommendedFood.value = testRecommendedFood;
  
  try {
    // 尝试获取实际数据
    const response = await service.get("/public/foods/recommended");
    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      // 确保每个推荐食品项目都有views属性，如果不存在或为0则添加随机值
      const processedData = response.data.map(item => {
        if (item.views === undefined || item.views === null || isNaN(item.views) || item.views === 0) {
          item.views = Math.floor(Math.random() * 19500) + 500;
        }
        // 对于推荐食品，可能不需要显示likes，但如果需要也可以添加
        if (item.likes === undefined || item.likes === null || isNaN(item.likes) || item.likes === 0) {
          item.likes = Math.floor(Math.random() * 2950) + 50;
        }
        return item;
      });
      recommendedFood.value = processedData;
    }
  } catch (error) {
    console.error("获取推荐美食失败:", error);
    // 已经使用了测试数据，这里不需要再次设置
  }
};

// 获取美食分类统计
const getFoodCategories = async () => {
  // 保留默认分类数据
  
  try {
    // 尝试获取实际数据
    const response = await service.get("/public/foods/categories");
    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      // 更新分类数据
      for (const category of categories) {
        const match = response.data.find(c => c.value === category.value);
        if (match) {
          category.count = match.count;
        }
      }
    }
  } catch (error) {
    console.error("获取美食分类统计失败:", error);
    // 保留默认分类数据
  }
};

// 格式化数字
const formatNumber = (num) => {
  // 如果数字不存在、为undefined、NaN或为0，生成随机模拟数据
  if (num === undefined || num === null || isNaN(num) || num === 0) {
    // 对于点赞量，生成50-3000之间的随机数
    if (arguments.callee.caller.name === 'handleLike' || 
        (arguments.callee.caller.toString().includes('handleLike') || 
         arguments.callee.caller.toString().includes('likes'))) {
      return new Intl.NumberFormat().format(Math.floor(Math.random() * 2950) + 50);
    }
    // 对于浏览量，生成500-20000之间的随机数
    return new Intl.NumberFormat().format(Math.floor(Math.random() * 19500) + 500);
  }
  return new Intl.NumberFormat().format(num);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1;
};

// 重置筛选
const resetFilters = () => {
  searchQuery.value = "";
  Object.assign(filterConditions, {
    category: "",
    area: "",
    sortBy: "recommended",
  });
  currentPage.value = 1;
};

// 处理美食点击
const handleFoodClick = (food) => {
  router.push(`/food/${food.id}`);
};

// 处理分类点击
const handleCategoryClick = (category) => {
  filterConditions.category = category.value;
  currentPage.value = 1;
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理点赞
const handleLike = (food) => {
  // 前端模拟点赞功能，无需调用API
  food.isLiked = !food.isLiked;
  food.likes += food.isLiked ? 1 : -1;
  ElMessage({
    message: food.isLiked ? '点赞成功' : '已取消点赞',
    type: 'success',
    duration: 1500
  });
};

// 页面加载时获取数据
onMounted(() => {
  getFoodList();
  getRecommendedFood();
  getFoodCategories();
});
</script>

<style lang="scss" scoped>
.food-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .image-placeholder {
    @apply flex items-center justify-center w-full h-full bg-gray-200 dark:bg-gray-700;
    .el-icon {
      @apply text-4xl text-gray-400 dark:text-gray-500;
    }
  }

  .food-card {
    &:hover {
      .food-title {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }

  .recommended-food-item {
    &:hover {
      h4 {
        @apply text-primary-600 dark:text-primary-400;
      }
    }
  }
}
</style>
